﻿(function ($) {
    ///needs to serialize form to json object
    $.fn.serializeJSON = function () {
        var json = {};
        jQuery.map($(this).serializeArray(), function (n, i) {
            json[n['name']] = n['value'];
        });
        return json;
    };
})(jQuery);


function InitAccordion(el, activeItemNr, onOpenItem, onNoElements, onResorted, onValidateItem) {///needs to create accordion with orderable items
    var li = el.find("li h3");
    if (li.length < 1 && typeof(onNoElements)=="function") {
        onNoElements();
        li = el.find("li h3");
    };
    var onChangeStart = function (event, ui, isValid) {
        if (!onOpenItem(ui, el)) {
            var oldLi = ui.oldHeader && ui.oldHeader.length > 0 ? ui.oldHeader.parent() : null;
            var newLi = ui.newHeader && ui.newHeader.length > 0 ? ui.newHeader.parent() : null;
            if (oldLi) {
                oldLi.removeClass("edit").addClass("changed");
                if (oldLi === false) oldLi.addClass("witherror"); else oldLi.removeClass("witherror");
                ui.oldContent.removeClass("shadow");
            }
            if (newLi) {
                newLi.addClass("edit");
                ui.newContent.addClass("shadow");
            }
        };
    };
    el.accordion({ active: activeItemNr, autoHeight: false, collapsible: true, animated: 'easeOutBounce', 'header': 'h3',
        changestart: function (event, ui) {
            if (typeof (onValidateItem) == "function")
                onChangeStart(event, ui, onValidateItem(event, ui, el));
            else
                onChangeStart(event, ui);
        },
        create: function (event, ui) {
            li.each(function (p, litm) {
                var h = $(litm).find(".item-info");
                if (h.length == 0) return;
                var k = h.find(".pos");
                if (k.length > 0) k.html(p + 1);
                else k = $("<span class=\"pos\"></span>").html(p + 1).appendTo(h);
            });
            el.sortable({ placeholder: "ui-state-highlight", update: function (event, ui) {
                if (typeof (onResorted) == "function") onResorted(event, ui, el);
            }
            });
            var activeUi = { newHeader: li.first() };
            if (activeItemNr && activeItemNr > 0) {
                ///already by options param been set: el.accordion("option", "active", activeItemNr);
                activeUi.newHeader = $(li[activeItemNr]);
            }
            activeUi.newContent = activeUi.newHeader.siblings().first();
            onChangeStart(null, activeUi, el);
        }
    });
}